<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务脚本编辑器</title>
    <!-- 引入Font Awesome图标库 -->
    <link href="./assets_files/font-awesome.min.css" rel="stylesheet">
    <!-- 引入CodeMirror库 -->
    <link rel="stylesheet" href="./assets_files/codemirror.min.css">
    <link rel="stylesheet" href="./assets_files/dracula.min.css">
    <script src="./assets_files/codemirror.min.js"></script>
    <script src="./assets_files/javascript.min.js"></script>
    <script src="./assets_files/matchbrackets.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }
        
        header {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        
        h1 {
            color: #2c3e50;
            font-size: 24px;
            font-weight: 600;
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #444;
        }
        
        .task-name-container {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        #taskName {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        #taskName:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        
        #openTaskBtn {
            background-color: #9b59b6;
            padding: 12px 20px;
        }
        
        #openTaskBtn:hover {
            background-color: #8e44ad;
        }
        
        .editor-container {
            position: relative;
            border: 1px solid #ddd;
            border-radius: 4px;
            transition: border-color 0.3s;
        }
        
        .editor-container:focus-within {
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        
        /* CodeMirror 编辑器样式 */
        #editorWrapper {
            width: 100%;
            min-height: 400px;
        }
        
        .CodeMirror {
            min-height: 400px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 14px;
            line-height: 1.5;
            border-radius: 4px;
        }
        
        .button-group {
            display: flex;
            justify-content: space-between; /* 两端对齐 */
        }
        
        button {
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.1s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        #testBtn {
            background-color: #2ecc71;
        }
        
        #testBtn:hover {
            background-color: #27ae60;
        }
        
        button:hover {
            background-color: #2980b9;
        }
        
        button:active {
            transform: translateY(1px);
        }
        
        button:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }
        
        button i {
            font-size: 18px;
        }
        
        .status-message {
            margin-top: 15px;
            padding: 10px 15px;
            border-radius: 4px;
            display: none;
        }
        
        .success {
            background-color: #dff0d8;
            color: #3c763d;
            display: block;
        }
        
        .error {
            background-color: #f2dede;
            color: #a94442;
            display: block;
        }
        
        /* 任务选择弹窗样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            display: none;
        }
        
        .modal {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        }
        
        .modal-header {
            padding: 16px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #777;
            padding: 0;
        }
        
        .modal-body {
            padding: 20px;
        }
        
        .task-list {
            list-style: none;
        }
        
        .task-item {
            padding: 12px 15px;
            border: 1px solid #eee;
            border-radius: 4px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .task-item:hover {
            background-color: #f5f7fa;
            border-color: #ddd;
        }
        
        .modal-footer {
            padding: 16px 20px;
            border-top: 1px solid #eee;
            text-align: right;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }
            
            .CodeMirror {
                min-height: 300px;
            }
            
            .button-group {
                flex-direction: column;
                gap: 10px;
            }
            
            button {
                width: 100%;
                justify-content: center;
            }
            
            .task-name-container {
                flex-direction: column;
                align-items: stretch;
            }
            
            #openTaskBtn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>接收任务JavaScript脚本编辑器</h1>
        </header>
        
        <form id="jsForm">
            <div class="form-group">
                <label>任务名称</label>
                <div class="task-name-container">
                    <input type="text" id="taskName" placeholder="请输入任务名称..." />
                    <button type="button" id="openTaskBtn">
                        <i class="fa fa-folder-open"></i> 打开
                    </button>
                </div>
            </div>
            
            <div class="form-group">
                <label for="jsEditor">JavaScript脚本</label>
                <div class="editor-container">
                    <div id="editorWrapper"></div>
                    <!-- 隐藏的textarea用于表单数据处理 -->
                    <textarea id="jsEditor" style="display: none;" placeholder="在这里编写JavaScript代码..."></textarea>
                </div>
            </div>
            
            <div class="button-group">
                <button type="button" id="testBtn">
                    <i class="fa fa-play"></i> 测试脚本
                </button>
                <button type="submit" id="saveBtn">
                    <i class="fa fa-save"></i> 保存脚本
                </button>
            </div>
            
            <div id="statusMessage" class="status-message"></div>
        </form>
    </div>
    
    <!-- 任务选择弹窗 -->
    <div class="modal-overlay" id="taskModal">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">选择任务</h3>
                <button type="button" class="close-modal" id="closeModal">×</button>
            </div>
            <div class="modal-body">
                <ul class="task-list" id="taskList">
                    <!-- 任务列表将通过JS动态填充 -->
                </ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="close-modal" id="cancelBtn">取消</button>
            </div>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const taskNameInput = document.getElementById('taskName');
        const jsEditorTextarea = document.getElementById('jsEditor');
        const saveBtn = document.getElementById('saveBtn');
        const testBtn = document.getElementById('testBtn');
        const statusMessage = document.getElementById('statusMessage');
        const jsForm = document.getElementById('jsForm');
        const openTaskBtn = document.getElementById('openTaskBtn');
        const taskModal = document.getElementById('taskModal');
        const closeModal = document.getElementById('closeModal');
        const cancelBtn = document.getElementById('cancelBtn');
        const taskList = document.getElementById('taskList');
        
        let codeMirrorEditor;
        
        // 页面加载时初始化编辑器
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化CodeMirror编辑器
            initEditor();
            
            // 绑定弹窗事件
            bindModalEvents();
        });
        
        // 初始化CodeMirror编辑器
        function initEditor() {
            codeMirrorEditor = CodeMirror(document.getElementById('editorWrapper'), {
                mode: "javascript", // 设置JavaScript模式
                theme: "dracula",   // 设置主题
                lineNumbers: true,  // 显示行号
                lineWrapping: true, // 自动换行
                matchBrackets: true, // 匹配括号
                indentUnit: 4,      // 缩进单位
                smartIndent: true,  // 智能缩进
                tabSize: 4,         // Tab键大小
                placeholder: "在这里编写JavaScript代码..."
            });
            
            // 同步编辑器内容到隐藏的textarea
            codeMirrorEditor.on('change', () => {
                jsEditorTextarea.value = codeMirrorEditor.getValue();
            });
        }
        
        // 绑定弹窗相关事件
        function bindModalEvents() {
            // 打开弹窗
            openTaskBtn.addEventListener('click', async () => {
                try {
                    // 从后台获取任务列表
                    const tasks = await fetchTaskList();
                    renderTaskList(tasks);
                    // 显示弹窗
                    taskModal.style.display = 'flex';
                } catch (error) {
                    showStatusMessage(`获取任务列表失败: ${error.message}`, 'error');
                }
            });
            
            // 关闭弹窗
            closeModal.addEventListener('click', () => {
                taskModal.style.display = 'none';
            });
            
            cancelBtn.addEventListener('click', () => {
                taskModal.style.display = 'none';
            });
            
            // 点击弹窗外部关闭
            taskModal.addEventListener('click', (e) => {
                if (e.target === taskModal) {
                    taskModal.style.display = 'none';
                }
            });
            
            // 任务列表点击事件委托
            taskList.addEventListener('click', async (e) => {
                const taskItem = e.target.closest('.task-item');
                if (taskItem) {
                    const taskId = taskItem.dataset.taskId;
                    if (taskId) {
                        try {
                            // 加载选中任务的脚本
                            await loadTaskScript(taskId);
                            // 关闭弹窗
                            taskModal.style.display = 'none';
                        } catch (error) {
                            showStatusMessage(`加载任务脚本失败: ${error.message}`, 'error');
                        }
                    }
                }
            });
        }
        
        // 从后台获取任务列表
        async function fetchTaskList() {
            const response = await fetch('/task/list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error('获取任务列表失败');
            }
            
            return await response.json();
        }
        
        // 渲染任务列表
        function renderTaskList(tasks) {
            // 清空现有列表
            taskList.innerHTML = '';
            
            if (tasks.length === 0) {
                const emptyItem = document.createElement('li');
                emptyItem.className = 'task-item';
                emptyItem.style.textAlign = 'center';
                emptyItem.style.cursor = 'default';
                emptyItem.textContent = '没有找到任务';
                taskList.appendChild(emptyItem);
                return;
            }
            
            // 添加任务项
            tasks.forEach(task => {
                const li = document.createElement('li');
                li.className = 'task-item';
                li.dataset.taskId = task.id;
                li.innerHTML = `
                    <strong>${task.name}</strong>
                    <div style="font-size: 12px; color: #777; margin-top: 4px;">
                        执行内容: ${task.memo || '未知'}
                    </div>
                `;
                taskList.appendChild(li);
            });
        }
        
        // 加载指定任务的脚本
        async function loadTaskScript(taskId) {
            const response = await fetch(`/task/script/${taskId}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'text/html; charset=utf-8'
                }
            });
            
            if (!response.ok) {
                throw new Error('加载任务脚本失败');
            }
            
            const data = await response.text();
            
            // 填充任务名称和脚本内容
            taskNameInput.value = taskId;
            codeMirrorEditor.setValue(data || '');
            jsEditorTextarea.value = data || '';
            
            showStatusMessage(`已加载任务: ${taskId}`, 'success');
        }
        
        // 保存脚本数据
        async function saveScriptData(scriptContent) {
            const taskName = taskNameInput.value.trim();
            if (!taskName) {
                showStatusMessage('任务名称不能为空', 'error');
                return false;
            }
            
            try {
                const response = await fetch(`/task/script/${taskName}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain; charset=utf-8'
                    },
                    body: scriptContent
                });
                
                if (!response.ok) {
                    throw new Error('保存数据失败');
                }
                
                return true;
                
            } catch (error) {
                console.error('保存数据时出错:', error);
                return false;
            }
        }
        
        // 测试脚本
        async function testScript(taskName, scriptContent) {
            if (!taskName) {
                taskName = "noname";
            }
            try {
                showStatusMessage('开始执行测试...', 'success');
                
                await fetch(`/task/test/${taskName}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain; charset=utf-8'
                    },
                    body: scriptContent
                })
                .then(response => {
                  if (!response.ok) {
                    return response.text().then(errorMessage => {
                      throw new Error(errorMessage);
                    });

                    throw new Error(`HTTP error! status: ${response.status}`);
                  }
                  return response.text();
                });
                
                showStatusMessage(`测试执行成功!`, 'success');
            } catch (error) {
                showStatusMessage(`测试执行出错: ${error.message}`, 'error');
            }
        }
        
        // 表单提交事件处理（保存）
        jsForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const scriptContent = codeMirrorEditor.getValue().trim();
            
            // 禁用保存按钮，防止重复提交
            saveBtn.disabled = true;
            saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 保存中...';
            
            // 保存数据
            const saveSuccess = await saveScriptData(scriptContent);
            
            // 恢复按钮状态
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="fa fa-save"></i> 保存脚本';
            
            // 显示保存结果
            if (saveSuccess) {
                showStatusMessage('脚本保存成功', 'success');
            } else {
                showStatusMessage('脚本保存失败，请重试', 'error');
            }
        });
        
        // 测试按钮点击事件
        testBtn.addEventListener('click', () => {
            const taskName = taskNameInput.value.trim();
            const scriptContent = codeMirrorEditor.getValue().trim();
            
            if (!scriptContent) {
                showStatusMessage('脚本不能为空', 'error');
                return;
            }
            
            // 禁用测试按钮，防止重复执行
            testBtn.disabled = true;
            testBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 测试中...';
            
            // 执行测试
            setTimeout(() => {
                testScript(taskName, scriptContent);
                
                // 恢复按钮状态
                testBtn.disabled = false;
                testBtn.innerHTML = '<i class="fa fa-play"></i> 测试脚本';
            }, 300);
        });
        
        // 显示状态消息
        function showStatusMessage(message, type) {
            statusMessage.textContent = message;
            statusMessage.className = 'status-message';
            statusMessage.classList.add(type);
            
            // 5秒后自动隐藏消息
            setTimeout(() => {
                statusMessage.classList.remove(type);
            }, 5000);
        }
    </script>
</body>
</html>